import random
from datetime import datetime,timedelta

from flask import Flask,session
from flask import current_app
from flask_session import Session
from flask_script import Manager

from info import create_app,models, db
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager
# 根据不同的key取不同的值
from info.models import User

app = create_app("develop")
# 创建manager对象管理app
manager = Manager(app)
# 使用Migrate关联app,db
Migrate(app,db)
# 给manager添加操作命令
manager.add_command("db",MigrateCommand)
# 创建管理员用户
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
def create_superuser(username, password):
    # 创建管理员用户
    admin = User()
    # 设置属性
    admin.nick_name = username
    admin.mobile = username
    admin.password = password
    admin.is_admin = True
    # 保存到数据库
    try:
        db.session.add(admin)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"
# 添加一千个老王
@manager.option('-t', '--test', dest='test')
def add_test_user(test):

    #定义用户容器
    user_list = []

    #创建测试用户,设置属性
    for i in range(0,1000):
        user = User()
        user.mobile = "138%08d"%i
        user.nick_name = "老王%d"%i
        user.password_hash = "pbkdf2:sha256:50000$lqdoIk7o$531930fae12b60573349ecdbac14ebb6c396551db5df859efa26ed05cbf4cf05"

        #最近31天以来登陆时间
        user.last_login = datetime.now() - timedelta(seconds=random.randint(0,3600*24*31))
        user_list.append(user)

    #添加数据库
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"

    return "创建成功"

if __name__ == '__main__':

    manager.run()